import Vue from 'vue'
import { appSetting } from '@/setting/app-setting'
import { login, logout, userInfo, getSmsCaptcha } from '@/api/user'

export const user = {
  state: {
    accessToken: '',
    hasUserInfo: false, // 标识是否获取了用户信息
    user: { // 用户信息
      id: '',
      username: '',
      nickname: '',
      realName: '',
      email: '',
      avatar: ''
    },
    rules: {}
  },

  getters: {
    user: state => state.user,
    hasUserInfo: state => state.hasUserInfo,
    nickname: state => state.user.nickname,
    avatar: state => state.user.avatar
  },

  mutations: {
    SET_TOKEN: (state, accessToken) => {
      state.accessToken = accessToken
    },

    SET_USER: (state, user) => {
      state.user = user
    },

    SET_RULES: (state, rules) => {
      state.rules = rules
    },

    CLEAR_USER: state => {
      state.user.id = ''
      state.user.username = ''
      state.user.nickname = ''
      state.user.realName = ''
      state.user.email = ''
      state.user.avatar = ''
    },

    TOGGLE_HAS_USER_INFO: (state, hasUserInfo) => {
      state.hasUserInfo = hasUserInfo
    }
  },

  actions: {
    // 登录
    login ({ commit }, { username, password }) {
      return new Promise((resolve, reject) => {
        login(username, password).then(rsp => {
          let { access_token, expires_in } = rsp
          commit('SET_TOKEN', access_token)
          Vue.ls.set(appSetting.token_key, access_token, expires_in * 60 * 1000)
          resolve(rsp)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出登录
    logout ({ commit, state }) {
      console.info('我执行了')
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_RULES', {})
          commit('CLEAR_USER')
          commit('TOGGLE_HAS_USER_INFO', false)
          Vue.ls.remove(appSetting.token_key)
          resolve()
        }).catch(error => {
          resolve(error)
        })
      })
    },

    // 获取用户信息
    userInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        userInfo().then(rsp => {
          let { user, rules } = rsp
          /*
          {
              user:{
              },
              rules:{
              }
          }
           */
          console.info(rsp)
          commit('SET_USER', user)
          commit('SET_RULES', rules)

          commit('TOGGLE_HAS_USER_INFO', true)
          resolve(rules)
        }).catch(error => {
          reject(error)
        })
      })
    },

    getSmsCaptcha ({ commit }, { mobile }) {
      return new Promise((resolve, reject) => {
        getSmsCaptcha(mobile).then(rsp => {
          resolve(rsp)
        }).catch(error => {
          reject(error)
        })
      })
    }

  }
}

export default user
